const fs = require('fs');
const execSync = require('child_process').execSync;

const getVersion = () => {
    const branch = execSync('git rev-parse --abbrev-ref HEAD', {encoding: 'utf8',})?.trim();
    const user = execSync('git show -s --format=%cn', {encoding: 'utf8',})?.trim();
    const commit = execSync('git show -s --format=%H', {encoding: 'utf8',})?.trim();
    const message = execSync('git show -s --format=%s', {encoding: 'utf8',})?.trim();
    return ` 
    /* --------------- 版本构建信息 --------------- */ 
    分支: ${branch} 
    提交: ${commit} 
    说明: ${message} 
    作者: ${user} 
    日期: ${new Date().toLocaleString()} 
    /* --------------- 版本构建信息 --------------- */
    `
};

const writeVersion = (path)=>{
    try {
        fs.writeFileSync(`${path}/version.txt`, getVersion(), {encoding: 'utf8'});
    } catch (e) {
        throw new Error(e);
    }
};


class WriteVersionPlugin { // 创建一个时间戳插件
    apply(compiler) {
        compiler.hooks.done.tap('WriteVersionPlugin', () => {
            writeVersion(compiler.options.output.path);
        });
    }
}

module.exports = WriteVersionPlugin;